﻿using System;
using System.IO;
using System.Collections;
using ICSharpCode.SharpZipLib.Zip;

namespace NetFtp.Core.Utils
{
    public class ZipUtils
    {
        /// <summary>
        /// Decompresser un fichier zip
        /// </summary>
        /// <param name="file">Fichier zip</param>
        /// <param name="folder">Dossier cible</param>
        /// <returns></returns>
        public static Queue Unzip(string file, string folder)
        {
            try
            {
                ZipInputStream zis = new ZipInputStream(new FileStream(file, FileMode.Open, FileAccess.Read));
                ZipEntry ze;
                Queue liste = new Queue();

                if (!Directory.Exists(folder))
                    Directory.CreateDirectory(folder);

                while ((ze = zis.GetNextEntry()) != null)
                {
                    if (ze.IsDirectory)
                        Directory.CreateDirectory(Path.Combine(folder, ze.Name));
                    else
                    {
                        if (!Directory.Exists(Path.Combine(folder, Path.GetDirectoryName(ze.Name))))
                            Directory.CreateDirectory(Path.Combine(folder, Path.GetDirectoryName(ze.Name)));

                        FileStream fos = new FileStream(Path.Combine(folder, ze.Name), FileMode.Create, FileAccess.Write);
                        int count;
                        byte[] buffer = new byte[4096];
                        while ((count = zis.Read(buffer, 0, 4096)) > 0)
                            fos.Write(buffer, 0, count);
                        fos.Close();
                    }
                    liste.Enqueue(ze.Name);
                }

                zis.Close();

                return liste;
            }
            catch
            {
                return null;
            }
        }
    }
}